<template>
    <view class="groupMembers">
        <view
            style="
                background: #fff;
                width: 750rpx;
                position: fixed;
                z-index: 100;
            "
            :style="{ height: systemInfo.statusBarHeight+'px'}"
        >
        </view>


        <view
                class="slim_header d-flex a-center j-center"
                style="border-bottom: none"
                :style="{ top: systemInfo.statusBarHeight + 'px' }"
            >
                <view class="left_box" @tap="goBack">
                    <image src="/static/center/back.png" class="back"></image>
                </view>
                <view class="title d-flex a-center j-between">收藏</view>
                <view class="right_box">
                    
                    <!-- <image src="/static/center/dian.png" class="dian"></image> -->
                </view>
            </view>


        <view
            class="content"
            :style="{ top: `calc(  100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <pullScroolView
                v-if="collectList.length"
                class="scrollView"
                ref="scroll"
                :pullDown="refresh"
                :pullUp="scrolltolower"
            >
                <view
                    class="card"
                    v-for="item in collectList"
                    :key="item.id"
                >
                    <view class="collect">
						<view v-if="item.content === 0" class="title">
						    <text class="text">{{item.contentValue.payload.text}}</text>
						</view>
                        <view v-if="item.content === 1" class="imgs d-flex d-r">
                            <image
                                :id="`img${item.id}${0}`"
                                @tap.stop="
                                    previewImage(
                                        `img${item.id}`,
                                        0,
                                        [item.contentValue.payload.imageInfoArray[2].url]
                                    )
                                "
                                class="img"
                                :src="item.contentValue.payload.imageInfoArray[0].url"
                                mode="aspectFill"
                            />
                        </view>
                        <view class="desp d-flex d-r">
                            <text class="text d-flex d-r a-center">
                                <text>
                                    {{ calcTimeForShow(item)}}
                                </text>
                            </text>
                        </view>

                        <view class="controls d-flex a-center j-between">
                            <view class="d-flex a-center">
                                <text class="text">{{item.typeValueName}}{{item.contentValue.conversationType == 'GROUP'?`-${item.contentValue.nick}`:``}}</text>
                            </view>
                            <view class="more d-flex a-center" @tap.stop="showControl(item)">
                                <view class="dian"></view>
                                <view class="dian"></view>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="heightBox"></view>
            </pullScroolView>

            <view
                v-if="!collectList.length"
                class="nodata d-flex d-c a-center j-center"
            >
                <image class="img" src="/static/nodata1.png"></image>

                <view class="desp d-flex d-c a-center j-center">
                    <view class="d-flex j-center"
                        ><text class="text">你还没有任何收藏</text></view
                    >
                </view>
            </view>
        </view>
    </view>
    <uni-popup ref="popup" type="bottom" :safe-area="false" background-color="transparent">
        <view class="popup_box">
            <view class="controls d-flex">
                <view class="control d-flex d-c a-center" @tap="openForward">
                    <i class="icon icon-jiantou" style="transform: rotate(250deg);"></i>
                    <view class="text">
                        转发
                    </view>
                </view>
				<!--
                <view class="control d-flex d-c a-center" @tap="goCollectConfig">
                    <i class="icon icon-zhanshifanwei"></i>
                    <view class="text">
                        修改展示范围
                    </view>
                </view>
				-->
                <view class="control d-flex d-c a-center" @tap="showDel">
                    <i class="icon icon-shanchu1"></i>
                    <view class="text">
                        删除
                    </view>
                </view>
            </view>
            <view style="height:20rpx;width:750rpx;background:#f5f5f5;"></view>
            <view class="bottom_button d-flex a-center j-center" @tap="popup.close()">
                <text class="text">取消</text>
            </view>
            <view class="heightBox"></view>
        </view>
    </uni-popup>
    <uni-popup
		ref="delPopup"
		type="bottom"
		:safe-area="false"
		background-color="transparent"
	>
		<view class="sys-confirm-content">
			<view class="confirm-content-title">确认删除该收藏?</view>
			<!-- <view class="confirm-content-tip">
				<view class="content-tip-row" style="color: #cc3300;">同时删除与该联系人的聊天记录</view>
			</view> -->
			<view  @tap="DelCollect" class="content-button button-confirm" style="color: #1DC691;">确认</view>
			<view style="height: 20rpx; background: #f5f5f5"></view>
			<view @tap="delPopup.close" class="content-button" style="color: #999999;">取消</view>
		</view>
	</uni-popup>
	<!--转发-->
	<view
	    v-if="forwardVisible"
	    class="slim_drawer_shadow"
	    :class="{ active: forwardActive }"
		@touchmove.stop.prevent="stop"
	    @tap="closeForward"
	></view>
	
	<view
		@touchmove.stop.prevent="stop"
	    v-if="forwardVisible"
	    class="slim_drawer"
	    :style="{ transform: `translateY(${drawTransFormHeight}px)` }"
	>
	    <view class="title">
	        <view class="left_button" @tap="closeForward">
	            <image class="arrow" src="/static/im/arrow-down.png"></image>
	        </view>
	        <text>选择一个聊天</text>
	        <!-- <view class="right_box">
	            </view> -->
	    </view>
	
	    <scroll-view
	        class="list_area"
	        :scroll-y="true"
	        :style="{ bottom: '20rpx' }"
	    >
	        <view
	            class="paddingBox"
	            :style="{
	                paddingBottom: systemInfo.safeAreaInsets?.bottom + 'px',
	            }"
	        >
	            <view class="search_box">
	                <image
	                    class="search_icon"
	                    src="/static/im/search.png"
	                ></image>
	                <input
	                    placeholder-style="color:#ccc"
	                    type="text"
	                    class="inp"
	                    :adjust-position="false"
	                    v-model="forwardSearch"
	                    placeholder="搜索"
	                />
	                <image
	                    v-if="forwardSearch"
	                    @tap="forwardSearch = ''"
	                    class="clear_icon"
	                    src="/static/im/close.png"
	                ></image>
	            </view>
	
	            <view class="near_forward">
	                <view
	                    v-if="forwardHistory && forwardHistory.length"
	                    class="sub_title"
	                    ><text class="text">最近转发</text></view
	                >
	                <view
	                    v-if="forwardHistory && forwardHistory.length"
	                    class="near_forward_list"
	                >
	                    <view
	                        class="box"
	                        v-for="item in forwardHistory"
	                        @tap="handleForwardSend(item)"
	                    >
	                        <image class="head" :src="item.chead"></image>
	                        <view class="text_box ell">
	                            <text class="text ell">{{
	                                item.forwardName
	                            }}</text>
	                        </view>
	                    </view>
	                    <!-- <view class="box">
	                        <image class="head" src="/static/img/1.jpg"></image>
	                        <view class="text_box ell">
	                            <text class="text ell">周杰伦111111111111</text>
	                        </view>
	                    </view>
	                    <view class="box">
	                        <image class="head" src="/static/img/1.jpg"></image>
	                        <view class="text_box ell">
	                            <text class="text ell">周杰伦111111111111</text>
	                        </view>
	                    </view>
	                    <view class="box">
	                        <image class="head" src="/static/img/1.jpg"></image>
	                        <view class="text_box ell">
	                            <text class="text ell">周杰伦111111111111</text>
	                        </view>
	                    </view>
	                    <view class="box">
	                        <image class="head" src="/static/img/1.jpg"></image>
	                        <view class="text_box ell">
	                            <text class="text ell">周杰伦111111111111</text>
	                        </view>
	                    </view> -->
	                </view>
	            </view>
	
	            <view class="sub_title"
	                ><text class="text">最近聊天</text></view
	            >
	
	            <view
	                class="row"
	                v-for="item in forwardList"
	                @tap="handleForwardSend(item)"
	            >
	                <image class="head" :src="item.chead"></image>
	                <view class="name"
	                    ><rich-text :nodes="item.nodes"></rich-text
	                ></view>
	                <!-- <text class="name"></text> -->
	                <!-- <view class="name"><rich-text :nodes="g.nodes"></rich-text></view> -->
	            </view>
	
	            <!-- <view class="row" v-for="item in forwardList">
	                <image
	                    class="head"
	                    :src="item.chead"
	                    @tap="handleForwardSend(item)"
	                ></image>
	                <view class="name" @tap="handleForwardSend(item)"
	                    ><rich-text :nodes="item.nodes"></rich-text
	                ></view>
	            </view> -->
	        </view>
	    </scroll-view>
	</view>
	<view class="dialog_box" v-if="forwardDialogVisible">
	    <view class="dialog_shadow"></view>
	    <view class="dialog_content">
	        <view class="paddingBox">
	            <view class="sub_title"><text class="text">发送给:</text></view>
	            <view class="forward_to">
	                <image
	                    class="head"
	                    :src="currentForwardConversion.chead"
	                ></image>
	                <view class="text_box ell">
	                    <text class="text ell">{{
	                        currentForwardConversion.forwardName
	                    }}</text>
	                </view>
	            </view>
	            <view class="forward_content">
	                <view
	                    class="text_box"
	                    v-if="currentMessage.type === 'TIMTextElem'"
	                >
	                    <text class="text">
	                        {{ currentMessage.payload.text }}
	                    </text>
	                </view>
	                <image
	                    v-if="currentMessage.type === 'TIMImageElem'"
	                    class="img"
	                    :style="{
	                        width:
	                            currentMessage.payload.imageInfoArray[1].width +
	                            'px',
	                        height:
	                            currentMessage.payload.imageInfoArray[1]
	                                .height + 'px',
	                    }"
	                    :src="currentMessage.payload.imageInfoArray[1].imageUrl"
	                ></image>
	
	                <view
	                    v-if="currentMessage.type === 'TIMVideoFileElem'"
	                    class="video_box psr"
	                    :style="{
	                        width: currentMessage.payload.snapshotWidth + 'px',
	                        height:
	                            currentMessage.payload.snapshotHeight + 'px',
	                    }"
	                >
	                    <image
	                        :style="{
	                            width:
	                                currentMessage.payload.snapshotWidth + 'px',
	                            height:
	                                currentMessage.payload.snapshotHeight +
	                                'px',
	                        }"
	                        :src="currentMessage.payload.snapshotUrl"
	                        class="video_img"
	                        mode="aspectFit"
	                    ></image>
	                    <image
	                        src="/static/im/video-play.png"
	                        class="video_play"
	                    ></image>
	                </view>
	            </view>
	        </view>
	
	        <view class="btns">
	            <view class="btn btn1" @tap="closeForwardDialog">
	                <text class="text">取消</text>
	            </view>
	            <view class="btn btn2" @tap="sendForwardMessage">
	                <text class="text">发送</text>
	            </view>
	        </view>
	    </view>
	</view>
    <imagePreview ref="preview"></imagePreview>
	
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from "vue";
import { onShow, onLoad, onUnload,onPageScroll } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { getUserFavorites,delUserFavorites,sendGroupMessage,sendUserMessage } from "@/api/api";
import imagePreview from "@/components/imagePreview.vue";
import { imStore as imStore1 } from "@/store/imStore";
import { forward } from "@/store/forward";
import { showLoading, closeLoading,generateSevenDigitRandomNumber } from "@/utils/utils";


onPageScroll((res) => {
    //const scrollTop = res.scrollTop;
    if(res.scrollTop === 0){
        backTop();
        setTimeout(()=>{
            uni.pageScrollTo({scrollTop:100});
        },100)
    }
});


const imStore: any = imStore1();
const scroll = ref();
const popup = ref();
const currentCollect:any = ref({});
const currentMessage:any = ref();
const backTop = ()=>{
    scroll.value.onBackTop();
}
const showControl = (collect:any)=>{
    currentCollect.value = collect;
	currentMessage.value = collect.contentValue
    popup.value.open();
}

const calcTimeForShow = computed(()=>(item:any)=>{
    const {createTime} = item;
	return fromNow(createTime)
})
const fromNow = (time:any) => {
    if (!time) {
        return "--";
    }
    return uni.$tm.u.getDateToNewData(time);
};



const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const collectList:any = ref([]);

const pageParam = reactive({
    page: 1,
    rows: 10,
    total: 0,
});
const goBack = () => {
    uni.navigateBack();
};

const GetUserFavorites = async () => {
    if (pageParam.total && collectList.value.length >= pageParam.total) {
        return;
    }
    const { page, rows } = pageParam;
    const params = {
        userId: userData.id,
        page,
        rows,
    };
    const res:any = await getUserFavorites(params);
    const { data } = res;
    pageParam.total = data.total;
    data.list.forEach((item:any) => {
		//JSON.parse(item.contentValue);  
        item.contentValue = JSON.parse(item.contentValue);
    });
    pageParam.page += 1;
    if (page === 1) {
        collectList.value = data.list;
    } else {
        collectList.value.push(...data.list);
    }
	console.log(collectList.value)
};



const refresh = async () => {
    pageParam.page = 1;
    pageParam.total = 0;
    await GetUserFavorites().catch(() => {});

    setTimeout(() => {
        scroll.value.success();
    }, 500);
};

const scrolltolower = async () => {
    await GetUserFavorites().catch(() => {});
};
const preview = ref();
const previewImage = (idPre: string, index: number, urls: any) => {
    uni.createSelectorQuery()
        .select(`#${idPre}${index}`)
        .boundingClientRect()
        .exec((ret) => {
            let params = {
                idPre,
                startInfo: [ret[0]], //图片的初始大小与位置
                index: index, //当前id
                urls: urls, //预览集合图片地址
            };
            preview.value.open(params);
        });
};
const delPopup = ref()
const showDel = ()=>{
    popup.value.close();
    setTimeout(()=>{
        delPopup.value.open();
    },300)

}
const DelCollect = async ()=>{
    delPopup.value.close();
    const res:any = await delUserFavorites({id:currentCollect.value.id});
    const {flag} = res;
    if(flag!==1){
        uni.showToast({
            icon: "none",
            title: "操作失败,请重试",
            duration: 1500,
        });
        return;
    }
    const index = collectList.value.findIndex((item:any)=>item.id===currentCollect.value.id)
    collectList.value.splice(index,1)
    pageParam.total-=1;

    uni.showToast({
        icon: "success",
        title: '已删除',
        duration: 1500,
    });
}
//转发
const keyboardHeight = ref(0);
const forwardVisible = ref(false);
const forwardActive = ref(false);
watch(forwardVisible, (val) => {
    nextTick(() => {
        forwardActive.value = val;
    });
});
const openForward = () => {
	popup.value.close();
    uni.hideKeyboard();
    formatForwardList();
    forwardVisible.value = true;
};
const forwardList: any = ref([]);
const allForwardList: any = ref([]);
const forwardSearch: any = ref("");
watch(forwardSearch, (newVal: any, oldVal: any) => {
    let str = newVal.trim();
    if (!str) {
        str = "";
    }
    //imStore.setConversationSearch(str);
    handleForwardSearch();
});
const handleForwardSearch = () => {
    if (!forwardSearch.value) {
        formatForwardList();
        return;
    }

    forwardList.value = allForwardList.value.filter((item: any) => {
        const str = item.forwardName;
        if (
            str.toLowerCase().search(forwardSearch.value.toLowerCase()) !== -1
        ) {
            return true;
        } else {
            return false;
        }
    });

    matchForwardHighLight();
};
const matchForwardHighLight = () => {
    const reg = new RegExp(forwardSearch.value, "gi");
    forwardList.value = forwardList.value.map((item: any) => {
        const obj = {
            ...item,
        };
        // const str = `<div style="color:#555;">${item.profile.nick}</div>`;

        const str = item.forwardName;

        const nodes = `<div style="color:#555;">${str.replace(reg, (s: any) => {
            return `<span style="color:#23e2a6">${s}</span>`;
        })}</div>`;

        obj.nodes = nodes;

        return obj;
    });
};
const handleForwardName = (item: any) => {
    let name = "";

    let group_nick = null;
    if (
        item.groupProfile &&
        item.groupProfile.selfInfo &&
        item.groupProfile.selfInfo.memberCustomField &&
        item.groupProfile.selfInfo.memberCustomField.length
    ) {
        item.groupProfile.selfInfo.memberCustomField.forEach((item) => {
            if (item.key === "group_nick") {
                group_nick = item.value;
            }
        });
    }

    switch (item.type) {
        case uni.$TIM.TYPES.CONV_C2C:
            name =
                item?.remark ||
                item?.userProfile.nick ||
                item?.userProfile?.userID ||
                "";
            break;
        case uni.$TIM.TYPES.CONV_GROUP:
            name =
                group_nick ||
                item.groupProfile.name ||
                item?.groupProfile?.groupID ||
                "";
            break;
        case uni.$TIM.TYPES.CONV_SYSTEM:
            name = "系统通知";
            break;
    }
    return name;
};

const handleForwardAvator = (item: any) => {
    let avatar = "";
    switch (item.type) {
        case uni.$TIM.TYPES.CONV_C2C:
            avatar =
                item?.userProfile?.avatar ||
                "https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_21.png";
            break;
        case uni.$TIM.TYPES.CONV_GROUP:
            avatar =
                item?.groupProfile?.avatar ||
                "https://web.sdk.qcloud.com/component/TUIKit/assets/group_avatar.png";
            break;
        case uni.$TIM.TYPES.CONV_SYSTEM:
            avatar =
                item?.groupProfile?.avatar ||
                "https://web.sdk.qcloud.com/component/TUIKit/assets/group_avatar.png";
            break;
    }
    return avatar;
};
const formatForwardList = () => {
    let list = imStore.conversationList.filter((item: any) => {
        return item.type === "C2C" || item.type === "GROUP";
    });
    list = JSON.parse(JSON.stringify(list));
	list = list.filter(item => item.conversationID !== 'C2C10001');
    list.sort((a: any, b: any) => {
        return b.lastMessage.lastTime - a.lastMessage.lastTime;
    });
	
    forwardList.value = list.map((item: any) => {
        let forwardName = handleForwardName(item);
        let chead = handleForwardAvator(item);
        return {
            ...item,
            forwardName,
            chead,
            nodes: `<div style="color:#555;">${forwardName}</div>`,
        };
    });

    allForwardList.value = JSON.parse(JSON.stringify(forwardList.value));
};
const FORWARD_STORE = forward();
const forwardHistory:any = computed(() => {
    return FORWARD_STORE.list;
});
const closeForward = () => {
    if (keyboardHeight.value) {
        /* #ifndef H5 */
        uni.hideKeyboard();
        /*#endif*/

        setTimeout(() => {
            forwardActive.value = false;
            nextTick(() => {
                setTimeout(() => {
                    forwardVisible.value = false;
                }, 300);
            });
        }, 400);
        return;
    }

    forwardActive.value = false;
    nextTick(() => {
        setTimeout(() => {
            forwardVisible.value = false;
        }, 300);
    });
};
const drawTransFormHeight = computed(() => {
    if (!forwardActive.value) {
        return uni.upx2px(1400);
    } else {
		return 0;
		/*
        if (keyboardHeight.value) {
            return -(systemInfo.windowHeight - uni.upx2px(1200)) - 50;
        } else {
            return 0;
        }
		*/
    }
});
const currentForwardConversion:any = ref({});
const handleForwardSend = (item: any) => {
    /* #ifndef H5 */
    uni.hideKeyboard();
    /*#endif*/
    currentForwardConversion.value = item;

    openForwardDialog();
    //closeForward();
};
const forwardDialogVisible = ref(false);
const openForwardDialog = () => {
    forwardDialogVisible.value = true;
};
const onKeyboardHeightChange = (obj: any) => {
    const { height } = obj;
    keyboardHeight.value = height;
};
const closeForwardDialog = () => {
    forwardDialogVisible.value = false;
};
const sendForwardMessage = async () => {
    showLoading();
	let jsonString = JSON.stringify(currentMessage.value.payload);
	jsonString = jsonString.replace(/uuid/g, "UUID");
	jsonString = jsonString.replace(/imageFormat/g, "ImageFormat");
	jsonString = jsonString.replace(/imageInfoArray/g, "ImageInfoArray");
	jsonString = jsonString.replace(/type/g, "Type");
	jsonString = jsonString.replace(/size/g, "Size");
	jsonString = jsonString.replace(/width/g, "Width");
	jsonString = jsonString.replace(/height/g, "Height");
	jsonString = jsonString.replace(/url/g, "URL");
	jsonString = jsonString.replace(/text/g, "Text");
	
	let MsgContent = JSON.parse(jsonString)
	if(currentMessage.value.type == "TIMImageElem"){
		MsgContent.ImageInfoArray.forEach((item:any) => {
			item.Type = item.Type + 1
		});
	}
	if(currentForwardConversion.value.type == "GROUP"){
		let params = {
			"GroupId": currentForwardConversion.value.groupProfile.groupID,
			"From_Account": userData.id, // 指定消息发送者（选填）
			"Random": generateSevenDigitRandomNumber(), // 随机数字，五分钟数字相同认为是重复消息
			"MsgBody": [ // 消息体，由一个element数组组成，详见字段说明
				{
				    "MsgType": currentMessage.value.type,
				    "MsgContent": MsgContent
				}
			]
		}
		sendGroupMessage(params).then((res:any) => {
			forwardVisible.value = false
			forwardDialogVisible.value = false
			closeLoading();
			if (res.errorCode === 0) {
			    uni.showToast({
			        icon: "none",
			        title: "已转发",
			        duration: 2000,
			    });
			}else{
				uni.showToast({
					icon: "none",
					title: "转发失败,请稍后再试",
					duration: 2000,
				});
			}
		}).catch(() => {
			closeLoading();
			uni.showToast({
				icon: "none",
				title: "转发失败,请稍后再试",
				duration: 2000,
			});
		});
	}
	
	if(currentForwardConversion.value.type == "C2C"){
		let params = {
			"SyncOtherMachine": 1, // 消息同步至发送方
			"From_Account": userData.id, // 指定消息发送者（选填）
			"To_Account": currentForwardConversion.value.userProfile.userID,
			"MsgRandom": generateSevenDigitRandomNumber(), // 随机数字，五分钟数字相同认为是重复消息
			"MsgBody": [ // 消息体，由一个element数组组成，详见字段说明
				{
				    "MsgType": currentMessage.value.type,
				    "MsgContent": MsgContent
				}
			]
		}
		sendUserMessage(params).then((res:any) => {
			forwardVisible.value = false
			forwardDialogVisible.value = false
			closeLoading();
			if (res.errorCode === 0) {
			    uni.showToast({
			        icon: "none",
			        title: "已转发",
			        duration: 2000,
			    });
			}else{
				uni.showToast({
					icon: "none",
					title: "转发失败,请稍后再试",
					duration: 2000,
				});
			}
		}).catch(() => {
			closeLoading();
			uni.showToast({
				icon: "none",
				title: "转发失败,请稍后再试",
				duration: 2000,
			});
		});
	}
};
const stop = ()=>{

}
//let  TUIGroupServer:any = null
onLoad(() => {
	//TUIGroupServer = new TUIGroupServer();
	//const TUIGroupServer: any = new TUIGroupServer();
	/* #ifndef H5 */
	uni.onKeyboardHeightChange(onKeyboardHeightChange);
	/*#endif*/
    setTimeout(() =>{
        uni.pageScrollTo({scrollTop:100});
    },100)
});

onUnload(() => {
	//TUIGroupServer.destroyed();
	/* #ifndef H5 */
	uni.offKeyboardHeightChange(onKeyboardHeightChange);
	/*#endif*/
});
onShow(() => {
    refresh();
});
</script>
<style lang="scss" scoped>
@import './collect.scss';
</style>
